﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using agsXMPP;
using agsXMPP.protocol.client;
using agsXMPP.protocol.iq.roster;
using agsXMPP.Xml.Dom;
using FirstFloor.ModernUI.Windows.Controls;
using Microsoft.Win32;
using YanMsg.APCode;
using System.Net.NetworkInformation;

namespace YanMsg.View
{
    /// <summary>
    /// Lgoin.xaml 的交互逻辑
    /// </summary>
    public partial class Login : UserControl
    {
        public static XmppClientConnection connection = null;

        public Login(string strUserName, string strPassword, string isAutoRun)
        {
            try
            {
                InitializeComponent();
                //设置登录按钮为焦点
                btDengLu.Focus();
                string strPTUrl = ConfigManger.ClientWebUrl + "login.aspx";
                GLPT.BBCode = "[url=" + strPTUrl + "]点击进入综合管理平台[/url]";
                if (strUserName != "")
                {
                    this.userNumber.Text = strUserName;
                    this.pwdBox.Text = strPassword;
                    Remember.IsChecked = true;
                }
                //如果自动登录为Y，则直接登录
                if (isAutoRun == "Y")
                {
                    AutoRun.IsChecked = true;
                    Loginevent();
                }
            }
            catch (Exception)
            {

            }


        }
        private void NetworkCallback(object sender, EventArgs e)
        {
            if (ConfigManger.ServerAutoLogin == "Y")
            {
                if (new ChatHelp().Ping(ConfigManger.ServerIP))
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 2));
                        if (UserData.notifyIcon.Icon == UserData.Icon_Offline)
                        {
                            Loginevent();
                        }
                    }));
                }
                else
                {
                    if (Application_Init.GetIconUserState() == "0")
                    {
                        Application_Init.notifyIconUserState(3);

                        this.Dispatcher.Invoke(new Action(() =>
                    {
                        UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ""));
                    }));
                    }
                }
            }
        }
        private void NetworkAcCallback(object sender, EventArgs e)
        {
            if (ConfigManger.ServerAutoLogin == "Y")
            {
                if (new ChatHelp().Ping(ConfigManger.ServerIP))
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 2));
                        if (UserData.notifyIcon.Icon == UserData.Icon_Offline)
                        {
                            Loginevent();
                        }
                    }));
                }
                else
                {
                    if (Application_Init.GetIconUserState() == "0")
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                   {
                       Application_Init.notifyIconUserState(3);
                       UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ""));
                   }));
                    }
                }
            }
        }
        //连接服务器失败的事件
        void con_OnError(object sender, Exception ex)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                //MsgManger.Show("无法连接服务器！请联系管理员." + ex.ToString());
                UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ""));
                Application_Init.notifyIconUserState(3);
                UserData.MainWindow.TimeAutoLJ.Start();

            }));
        }
        void con_ConnectionState(object sender, XmppConnectionState State)
        {
            if (State == XmppConnectionState.Disconnected)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    // MsgManger.ShowTuiTip("网络出现问题,无法连接服务器!");服务器关闭时触发
                    UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, ConfigManger.ClientPassword, ""));
                    Application_Init.notifyIconUserState(3);
                    UserData.MainWindow.TimeAutoLJ.Start();

                }));
            }
        }

        //(用来处理用户上线下线)
        void con_OnPresence(object sender, Presence pres)
        {
            //用户上线
            if (pres.Show == ShowType.chat)
            {
                if (pres.From.User != connection.MyJID.User)
                {
                    vw_Yan_Chat_user Item = UserData.ListPeople.Where(d => d.UserName == pres.From.User).SingleOrDefault();
                    Item.ISonline = "Y";
                    Item.UserIPAdress = pres.Value;
                }
            }
            else if (pres.Type == PresenceType.unavailable)//用户下线
            {
                vw_Yan_Chat_user Item = UserData.ListPeople.Where(d => d.UserName == pres.From.User).SingleOrDefault();
                Item.ISonline = "N";
                Item.UserIPAdress = "";
            }
            this.Dispatcher.Invoke(new Action(() =>
            {
                MainPeopleList.ModifyPeopleTree();
            }));
        }

        //在线用户
        void XmppCon_OnRosterItem(object sender, RosterItem pres)
        {
            vw_Yan_Chat_user Item = UserData.ListPeople.Where(d => d.UserName == pres.Name).SingleOrDefault();
            Item.ISonline = "Y";
            Item.UserIPAdress = pres.Value;
        }

        //更新用户在线信息
        void XmppCon_OnRosterEnd(object sender)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                MainPeopleList.ModifyPeopleTree();
            }));

        }


        void Loginevent()
        {
            connection = new XmppClientConnection();
            connection.OnLogin += new ObjectHandler(con_OnLogin);
            //验证事件
            connection.OnAuthError += new XmppElementHandler(con_OnAuthError);
            //出息消息
            connection.OnPresence += new PresenceHandler(con_OnPresence);
            //connection.OnRosterStart += new ObjectHandler(XmppCon_OnRosterStart);
            connection.OnRosterEnd += new ObjectHandler(XmppCon_OnRosterEnd);
            connection.OnRosterItem += new XmppClientConnection.RosterHandler(XmppCon_OnRosterItem);
            connection.OnSocketError += new ErrorHandler(con_OnError);
            connection.OnXmppConnectionStateChanged += new XmppConnectionStateHandler(con_ConnectionState);
            connection.AutoAgents = false;
            connection.AutoPresence = false;
            connection.Username = userNumber.Text;
            connection.Password = pwdBox.Text;
            //该属性意思为自动解析后面提到的connectserver属性，设置为true就会解析server属性即会利用System.Net.DNS.Resolve方法来将域名映射成ip地址
            connection.AutoResolveConnectServer = false;
            connection.ConnectServer = ConfigManger.ServerIP;
            connection.Port = int.Parse("9070");
            connection.Resource = userNumber.Text;
            connection.UseCompression = true;
            this.Dispatcher.Invoke(new Action(() =>
            {
                UserData.MainWindow.Wait();
            }));
            connection.Open();


        }


        //登录事件
        private void btDengLu_Click(object sender, RoutedEventArgs e)
        {
            Loginevent();
            if (Remember.IsChecked == true)
            {
                new ConfigManger().SetConfig("ClientUserName", userNumber.Text);
                new ConfigManger().SetConfig("ClientPassword", pwdBox.Text);
            }
            else
            {
                new ConfigManger().DelConfig("ClientUserName");
                new ConfigManger().DelConfig("ClientPassword");
            }

            if (AutoRun.IsChecked == true)
            {
                new ConfigManger().SetConfig("ClientisAutoRun", "Y");
            }
            else
            {
                new ConfigManger().DelConfig("ClientisAutoRun");
            }

        }
        //验证出错
        void con_OnAuthError(object sender, Element e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                MsgManger.Show("用户名或密码不正确！");
                UserData.MainWindow.ReturnPage(new Login(ConfigManger.ClientUserName, "", ""));
                UserData.MainWindow.TimeAutoLJ.Stop();//停止断线自动登录
            }));
        }
        //验证完成并登录
        void con_OnLogin(object sender)
        {
            connection.Show = ShowType.chat;
            connection.SendMyPresence();
            this.Dispatcher.Invoke(new Action(() =>
            {
                UserData.MainWindow.AddPage(new FriendList());
                UserData.MainWindow.TimeAutoLJ.Stop();//停止断线自动登录
                Application_Init.notifyIconUserState(0);
                Application_Init.maininit();
                UserData.MainWindow.imgSysSet.Visibility = Visibility.Visible;

            }));
        }


        //记住密码
        private void Remember_Click(object sender, RoutedEventArgs e)
        {
            if (Remember.IsChecked != true)
            {
                AutoRun.IsChecked = false;
            }
        }

        //自动登录
        private void AutoRun_Click(object sender, RoutedEventArgs e)
        {
            if (AutoRun.IsChecked == true)
            {
                Remember.IsChecked = true;
            }
        }

        private void Login_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Loginevent();
            }

        }







    }

}
